package com.example.springdata.service;

import com.example.springdata.model.User;
import com.example.springdata.repository.UserRepository;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Service
public class UserService {

    private UserRepository userRepository;

    private StringRedisTemplate stringRedisTemplate;

    public UserService(UserRepository userRepository, StringRedisTemplate stringRedisTemplate) {
        this.userRepository = userRepository;
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Cacheable(value = "user", key = "'user' + #id")
    public User getById(Long id) {
        return userRepository.findById(id).orElse(null);
    }

//    public User getById(Long id) {
//        String key = "user:" + id;
//        User user = null;
//
//        ObjectMapper mapper = new ObjectMapper();
//        String jsonStr = stringRedisTemplate.opsForValue().get(key);
//        if (jsonStr != null) {
//            try {
//                user = mapper.readValue(jsonStr, User.class);
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        } else  {
//            user = userRepository.findOne(id);
//            try {
//                jsonStr =  mapper.writeValueAsString(user);
//                stringRedisTemplate.opsForValue().set(key, jsonStr, 30, TimeUnit.SECONDS);
//            } catch (JsonProcessingException e) {
//                e.printStackTrace();
//            }
//        }
//
//        return user;
//    }
}
